package com.block.product.service.union;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import com.block.product.service.utils.RongYouKeUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class KeDaiUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();
    @Autowired
    private MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(true);
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String mobileMd5 = SecureUtil.md5(uniLoginDTO.getMobile()).toLowerCase();
        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectByMobileMd5(mobileMd5);

        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("name", memberSourceInfo.getRealname());
        bizmMap.put("userPhone", memberSourceInfo.getMobile());
        bizmMap.put("age", memberSourceInfo.getAge());
        bizmMap.put("city", memberSourceInfo.getCity());
        bizmMap.put("sex", memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizmMap.put("loanAmount", RongYouKeUtils.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizmMap.put("monthlyIncome", RongYouKeUtils.getSalaryPay(memberSourceInfo.getShouru()));
        bizmMap.put("qualification", RongYouKeUtils.getXueLi(memberSourceInfo.getXueli()));
        bizmMap.put("profession", RongYouKeUtils.getJob(memberSourceInfo.getGongzuo()));
        bizmMap.put("gjj", RongYouKeUtils.getGjj(memberSourceInfo.getGjj()));
        bizmMap.put("socialInsurance", RongYouKeUtils.getSheBao(memberSourceInfo.getShebao()));
        bizmMap.put("house", RongYouKeUtils.getHouse(memberSourceInfo.getHouse()));
        bizmMap.put("car", RongYouKeUtils.getCar(memberSourceInfo.getCar()));
        bizmMap.put("sesame", RongYouKeUtils.getZhiMa(memberSourceInfo.getZhima()));
        bizmMap.put("insurancePolicy", RongYouKeUtils.getBaoXian(memberSourceInfo.getBaoxian()));

        String content = encrypt(JSON.toJSONString(bizmMap), apiInfoParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelCode", apiInfoParam.getApiCode());
        paramMap.put("content", content);

        log.info("【可贷】联登开始【queryUrl】{}【bizMap】{}【paramMap】{}", checkUrl,JSON.toJSONString(bizmMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【可贷】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        loginResult.setCode(String.valueOf(code));
        loginResult.setMessage(message);
        loginResult.setResultInfo(result);

        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(String.valueOf(code), "0")) {
            JSONObject data = resultObject.getJSONObject("data");
                String url = data.getString("url");
                loginResult.setSuccess(true);
                loginResult.setLoginUrl(url);
        }
        return loginResult;
    }


    public static String encrypt(String contentStr, String key) {
        try {
            if(StringUtils.isEmpty(contentStr)) {
                return null;
            }
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(contentStr.getBytes(StandardCharsets.UTF_8));
            return new org.apache.commons.codec.binary.Base64().encodeToString(encrypted);
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
